package com.classloader;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author: csh
 * @Date: 2021/12/25 16:34
 * @Description:
 */
public class MyClassLoader extends ClassLoader{
    private String byteCodePath;

    public MyClassLoader(String byteCodePath) {
        this.byteCodePath = byteCodePath;
    }

    public MyClassLoader(ClassLoader parent, String byteCodePath) {
        super(parent);
        this.byteCodePath = byteCodePath;
    }

    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        BufferedInputStream bis = null;
        ByteArrayOutputStream baos = null;
        try {
            //获取字节码文件的完整 路劲
            String fileName = byteCodePath + className + ".class";
            //获取一个输入流
             bis = new BufferedInputStream(new FileInputStream(fileName));
             //获取一个输出流
             baos = new ByteArrayOutputStream();

            int len;
            byte[] data = new byte[1024];
            while ((len = bis.read(data)) !=-1){
                baos.write(data,0,len);
            }
            //获取内存中的完整的字节数组的数据
            byte[] byteCodes = baos.toByteArray();
            //调用defineClass(),将字节数组的数据转换为C的实例。
            defineClass(null,byteCodes,0,byteCodes.length);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                baos.close();
                bis.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
